<script setup>
import LimitFram from "./LimitFrame.vue";
import TimeRules from "./TimeRules.vue";
import { deepClone } from "@/utils";
const props = defineProps({
  limit: {
    type: Object,
    required: true,
  },
});

const timeRuleVisible = ref(false),
  form = ref({}),
  submitLoading = ref(false);

const timeRuleRef = ref();

const emits = defineEmits(["cancel"]);

// 描述
const ruleText = computed(() => {
  let rule = props.limit.value;
  let week = {
    1: "周一",
    2: "周二",
    3: "周三",
    4: "周四",
    5: "周五",
    6: "周六",
    7: "周日",
  };
  if (!rule.type) return "";
  let text = rule.type == 1 ? "每周 | " : "每月 | ";
  if (rule.type == 1) {
    text += rule.day
      .split(",")
      .map((item) => week[item])
      .join("、");
  } else {
    text += rule.day
      .split(",")
      .map((item) => {
        return item + "号";
      })
      .join("、");
  }
  text += " | " + rule.startTime + "~" + rule.endTime;
  return text;
});

const editRule = () => {
  form.value = deepClone(props.limit.value);
  timeRuleVisible.value = true;
};

const addRule = () => {
  form.value = {};
  timeRuleVisible.value = true;
};

const onConfirm = async () => {
  const rs = await timeRuleRef.value.save();
  if (rs) {
    timeRuleVisible.value = false;
    props.limit.value = form.value;
    formatLimit();
  }
};

const onClose = () => {
  emits("cancel");
};

// 生成表达式
const formatLimit = () => {
  let propertyKey = {};
  let propertyKeyStr = ""
  let propertyKeyList = []
  let rule = props.limit.value;

  let key = `${rule.type == 1 ? "weekDay" : "monthDay"}`;
  let days = rule.day.split(",").map((day) => `$_system.${key}==${day}`);

  propertyKey[key] = true;
  props.limit.expression = `((${days.join("||")})&&($_system.time>${Number(
    rule.startTime.split(":").join("")
  )}&&$_system.time<${Number(rule.endTime.split(":").join(""))}))`;

  propertyKeyStr = `${propertyKey.weekDay ? "weekDay," : ""}${
    propertyKey.monthDay ? "monthDay," : ""
  }time`;
  // props.limit.propertyType = 0;
  // props.limit.businessType = "system";


  propertyKeyStr.split(",").forEach(item=>{
    propertyKeyList.push(
      {
        businessType: "system",
        key: item,
      }
    )
  })

  props.limit.keys = propertyKeyList
  console.log('[ props.limit ]', props.limit)
};

defineExpose({ add: addRule });
</script>
<template>
  <LimitFram title="时间限制" :content="ruleText" @edit="editRule" />
  <Dialog
    v-model="timeRuleVisible"
    title="时间限制"
    :width="500"
    :loading="submitLoading"
    @close="onClose"
    @confirm="onConfirm"
  >
    <time-rules
      ref="timeRuleRef"
      v-model="form"
      v-if="timeRuleVisible"
    ></time-rules>
  </Dialog>
</template>
<script>
export default {
  name: "TimeLimit",
};
</script>
